import MainSc from "./MainSc";
import { GameLocalStorage } from "./ComClass";
import { Msger } from "./Msger";
import BallAndBianBianSc from "./BallAndBianBianSc";

// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class MainBianBianSc extends cc.Component {

    @property(cc.Prefab)
    bianbian: cc.Prefab = null;

    // LIFE-CYCLE CALLBACKS:

    onLoad() {

        Msger.on(Msger.on_game_remove_ball, <any>this.on_game_remove_ball, this);
    }

    start() {

    }
    private on_game_remove_ball(node, blast) {
        if (blast) {
            let ballsc = node.getComponent(BallAndBianBianSc);
            if (ballsc) {
                ballsc.DestroyBianbian();                
            }
            ballsc = blast.getComponent(BallAndBianBianSc);
            if (ballsc) {
                ballsc.DestroyBianbian();
            }
        }
    }
    private getDistance(x1, y1, x2, y2): number {
        return Math.floor(Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)));
    }
    private addTimer = 0;
    private beginLevel = 3;
    update(dt) {
        let level = GameLocalStorage.gameData.level;
        if (level >= this.beginLevel) {
            let max = 10 - (level - this.beginLevel) * 1.5;
            this.addTimer += dt;
            if (this.addTimer >= max) {
                this.addOneBianbian();
                this.addTimer = 0;
            }
        }
    }
    private ballsLayer: cc.Node;
    private addOneBianbian() {
        if (!this.ballsLayer) {
            this.ballsLayer = this.getComponent(MainSc).ballsLayer;
        }
        //出一个便便
        let bianbian = cc.instantiate(this.bianbian);
        bianbian.rotation = Math.random() * 360;
        //bianbian.x = Math.random() * (166 * 2) - 166;
        bianbian.x = Math.random() < 0.5 ? -152 : 152;
        //bianbian.y = -366 - Math.random() * (400 - 366);
        bianbian.y = 700;
        this.ballsLayer.addChild(bianbian);
        // bianbian.scale = 0.5;
        // bianbian.runAction(cc.scaleTo(1, 1, 1));
    }
}
